package com.nari.ncps.screen.service.impl.ne;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.ne.NePopupSafe;
import com.nari.ncps.screen.entity.ne.NeProdoperPowerGs;
import com.nari.ncps.screen.entity.ne.NeProdoperSalesPurchase;
import com.nari.ncps.screen.mapper.ne.NeProdoperPowerGsMapper;
import com.nari.ncps.screen.service.ne.NeProdoperPowerGsService;
import com.nari.ncps.screen.vo.ne.NePowerGenerationAnnualVO;
import com.nari.ncps.screen.vo.ne.NePowerGenerationDailyVO;
import com.nari.ncps.screen.vo.ne.NePowerGenerationMonthlyVO;
import com.nari.ncps.screen.vo.ne.WindPowerGenerationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 新能源发电情况统计表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperPowerGsServiceImpl extends ServiceImpl<NeProdoperPowerGsMapper, NeProdoperPowerGs> implements NeProdoperPowerGsService {

    @Autowired
    private NeProdoperPowerGsMapper neProdoperPowerGsMapper;

    @Override
    public List<NePowerGenerationAnnualVO> getAnnualPowerGeneration(Integer year) {
        // 如果年份参数为空，默认使用当前年份
        // 1. 确定查询的年份范围
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);

        // 如果指定了年份，查询该年份及之前4年；否则查询最近5年
        int endYear = (year != null) ? year : currentYear;
        int startYear = endYear - 4;
        // 2. 查询指定年份范围内的所有销售数据
        LambdaQueryWrapper<NeProdoperPowerGs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeProdoperPowerGs::getOrgCode, "100360")//根据orgcode来查询是哪个公司的，如果没有传orgcode那么就会按照内蒙公司的维度进行查询
                .eq(NeProdoperPowerGs::getDateType, 0);
        queryWrapper.ge(NeProdoperPowerGs::getYear, startYear).le(NeProdoperPowerGs::getYear, endYear).orderByAsc(NeProdoperPowerGs::getYear);
        List<NeProdoperPowerGs> allData = this.list(queryWrapper);
        // 循环遍历allData，将相同year的plannedGeneration和actualGeneration相加
        Map<Integer, NeProdoperPowerGs> yearMap = new HashMap<>();
        for (NeProdoperPowerGs data : allData) {
            Integer yearKey = data.getYear();
            if (yearMap.containsKey(yearKey)) {
                // 如果已存在该年份，则累加数值
                NeProdoperPowerGs existing = yearMap.get(yearKey);
                existing.setPlannedGeneration(existing.getPlannedGeneration().add(data.getPlannedGeneration()));
                existing.setActualGeneration(existing.getActualGeneration().add(data.getActualGeneration()));
            } else {
                // 如果不存在，则添加到map中
                yearMap.put(yearKey, data);
            }
        }
        List<NePowerGenerationAnnualVO> resultList = new ArrayList<>();
        yearMap.forEach((newYear, data) -> {
            NePowerGenerationAnnualVO vo = new NePowerGenerationAnnualVO();
            vo.setYear(newYear);
            vo.setPlannedGeneration(data.getPlannedGeneration());
            vo.setActualGeneration(data.getActualGeneration());
            resultList.add(vo);
        });
        //        升序
        resultList.sort(Comparator.comparing(NePowerGenerationAnnualVO::getYear));
        return resultList;
    }


    @Override
    public List<NePowerGenerationMonthlyVO> getMonthlyPowerGeneration(Integer year) {
        // 1. 确定查询的年份范围
        YearMonth currentYearMonth = YearMonth.now();
        String current = currentYearMonth.format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 获取12个月之前的年月
        YearMonth twelveMonthsAgo = YearMonth.now().minusMonths(11);
        String startDate = twelveMonthsAgo.format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 2. 查询指定年份范围内的所有销售数据
        LambdaQueryWrapper<NeProdoperPowerGs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeProdoperPowerGs::getOrgCode, "100360")//根据orgcode来查询是哪个公司的，如果没有传orgcode那么就会按照内蒙公司的维度进行查询
                .eq(NeProdoperPowerGs::getDateType, 1)
                .ge(NeProdoperPowerGs::getStatisticTime, startDate)
                .le(NeProdoperPowerGs::getStatisticTime, current)
                .orderByAsc(NeProdoperPowerGs::getStatisticTime);

        // 从数据库查询指定年份的月度发电数据（date_type = 1）
        List<NeProdoperPowerGs> dataList = this.list(queryWrapper);
        // 如果数据为空，返回空列表
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
        }
        List<NePowerGenerationMonthlyVO> resultList = new ArrayList<>();
        for (NeProdoperPowerGs data : dataList) {
            NePowerGenerationMonthlyVO vo = new NePowerGenerationMonthlyVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());
            vo.setPlannedGeneration(data.getPlannedGeneration());
            vo.setActualGeneration(data.getActualGeneration());
            resultList.add(vo);
        }
        return resultList;
    }

    @Override
    public List<NePowerGenerationDailyVO> getDailyPowerGeneration(Integer year) {
        // 如果年份参数为空，默认使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
// 获取七天前的日期
        LocalDate sevenDaysAgo = currentDate.minusDays(6); // 包含当天，共7天
        // 格式化为 yyyyMMdd
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String current = currentDate.format(formatter);
        String sevenDaysAgoStr = sevenDaysAgo.format(formatter);
        // 2. 查询指定年份范围内的所有销售数据
        LambdaQueryWrapper<NeProdoperPowerGs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeProdoperPowerGs::getOrgCode, "100360")//根据orgcode来查询是哪个公司的，如果没有传orgcode那么就会按照内蒙公司的维度进行查询
                .eq(NeProdoperPowerGs::getDateType, 2)
                .ge(NeProdoperPowerGs::getStatisticTime, sevenDaysAgoStr)
                .le(NeProdoperPowerGs::getStatisticTime, current);;

        // 从数据库查询指定年份的日发电数据（date_type = 2）
        List<NeProdoperPowerGs> dataList = this.list(queryWrapper);
        // 如果数据为空，返回空列表
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
        }
        List<NePowerGenerationDailyVO> resultList = new ArrayList<>();
        for (NeProdoperPowerGs data : dataList) {
            NePowerGenerationDailyVO vo = new NePowerGenerationDailyVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());
            vo.setDay(data.getDay());
            vo.setPlannedGeneration(data.getPlannedGeneration());
            vo.setActualGeneration(data.getActualGeneration());
            resultList.add(vo);
        }
        return resultList;
    }

    @Override
    public WindPowerGenerationVO getWindPowerGeneration(String orgCode) {
        if (orgCode == null) {
            orgCode = "134058";
        }
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取七天前的日期
        LocalDate sevenDaysAgo = currentDate.minusDays(6); // 包含当天，共7天
        // 格式化为 yyyyMMdd
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String current = currentDate.format(formatter);
        String sevenDaysAgoStr = sevenDaysAgo.format(formatter);

        //查询三级单位的七天内的发电情况
        LambdaQueryWrapper<NeProdoperPowerGs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeProdoperPowerGs::getOrgCode, orgCode)//根据orgcode来查询是哪个公司的，如果没有传orgcode那么就会按照内蒙公司的维度进行查询
                .eq(NeProdoperPowerGs::getDateType, 2).ge(NeProdoperPowerGs::getStatisticTime, sevenDaysAgoStr).le(NeProdoperPowerGs::getStatisticTime, current);
        List<NeProdoperPowerGs> allData = this.list(queryWrapper);
        WindPowerGenerationVO vo = new WindPowerGenerationVO();
        List<WindPowerGenerationVO.PowerGenerationItem> list = new ArrayList<>();
        for (NeProdoperPowerGs data : allData) {
            WindPowerGenerationVO.PowerGenerationItem item = new WindPowerGenerationVO.PowerGenerationItem();
            item.setTime(data.getDay().toString());
            item.setPowerGeneration(data.getActualGeneration());
            list.add(item);
        }
        vo.setTrendData(list);
        return vo;
    }
}
